# @Time : 2021/10/25 20:52
# @Author : Li Kunlun
# @Description : 使用线程池在web服务中实现加速

# https://blog.csdn.net/han2529386161/article/details/103592862
# https://blog.csdn.net/daijiguo/article/details/78042309
# https://blog.csdn.net/qq_35869630/article/details/105876923?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522163516814816780271565862%2522%252C%2522scm%2522%253A%252220140713.130102334.pc%255Fall.%2522%257D&request_id=163516814816780271565862&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2~all~first_rank_ecpm_v1~rank_v31_ecpm-5-105876923.pc_search_result_control_group&utm_term=python%E5%A4%9A%E7%BA%BF%E7%A8%8B%E9%81%87%E5%88%B0io%E6%97%B6%E9%87%8A%E6%94%BEgil+%E4%BC%9A%E5%8A%A0%E5%BF%AB%E6%89%A7%E8%A1%8C%E9%80%9F%E5%BA%A6&spm=1018.2226.3001.4187

import flask
import json
import time
from concurrent.futures import ThreadPoolExecutor

app = flask.Flask(__name__)
# 初始化全局线程池
pool = ThreadPoolExecutor()


def read_file():
    time.sleep(0.1)  # 相当于io操作
    return "read_file result"


def read_db():
    time.sleep(0.2)
    return "read_db result"


def read_api():
    time.sleep(0.3)
    return "read_api result"


@app.route("/")
def index():
    # 返回的不再是字符串，而是三个future对象
    result_file = pool.submit(read_file)
    result_db = pool.submit(read_db)
    result_api = pool.submit(read_api)
    return json.dumps({
        "result_file": result_file.result(),
        "result_db": result_db.result(),
        "result_api": result_api.result()
    })


if __name__ == '__main__':
    app.run()
